const { ethers } = require('ethers');

// BSC Testnet配置
const BSC_TESTNET_RPC = 'https://data-seed-prebsc-1-s1.binance.org:8545/';
const CONTRACT_ADDRESS = '0x031b8B821B0F1A87D1a1451479d29660Bc68d2C8';

// 合约ABI（只包含需要的方法）
const contractABI = [
  "function tokenLaunches(uint256) external view returns (address tokenAddress, address creator, string name, string symbol, string description, string website, string telegram, string twitter, uint256 targetAmount, uint256 raisedAmount, uint256 tokensSold, uint256 createdAt, uint256 deadline, uint256 bondingCurveK, uint256 totalSupplyForSale, bool launched, bool cancelled)",
  "function calculateBNBForTokens(uint256 _launchId, uint256 _tokenAmount) external view returns (uint256)",
  "function getCurrentTokenPrice(uint256 _launchId) external view returns (uint256)"
];

// ERC20 Token ABI
const tokenABI = [
  "function balanceOf(address owner) external view returns (uint256)",
  "function allowance(address owner, address spender) external view returns (uint256)"
];

async function checkSellConditions() {
  console.log('🔍 检查代币出售条件...\n');
  
  try {
    // 连接到BSC Testnet
    const provider = new ethers.JsonRpcProvider(BSC_TESTNET_RPC);
    const contract = new ethers.Contract(CONTRACT_ADDRESS, contractABI, provider);
    
    const launchId = 2;
    const tokenAmount = ethers.parseUnits('10', 18); // 10 tokens
    const userAddress = '0x694B96b770f607Da56289824fcD18818cd479F29';
    
    console.log('参数:');
    console.log('- LaunchId:', launchId);
    console.log('- Token Amount:', ethers.formatUnits(tokenAmount, 18));
    console.log('- User Address:', userAddress);
    console.log('');
    
    // 1. 获取合约BNB余额
    const contractBalance = await provider.getBalance(CONTRACT_ADDRESS);
    console.log('1. 合约BNB余额:', ethers.formatEther(contractBalance), 'BNB');
    
    // 2. 获取launch信息
    const launch = await contract.tokenLaunches(launchId);
    console.log('2. Launch信息:');
    console.log('   - Token Address:', launch.tokenAddress);
    console.log('   - Raised Amount:', ethers.formatEther(launch.raisedAmount), 'BNB');
    console.log('   - Tokens Sold:', ethers.formatUnits(launch.tokensSold, 18));
    console.log('   - Launched:', launch.launched);
    console.log('   - Cancelled:', launch.cancelled);
    console.log('');
    
    // 3. 获取用户代币余额
    const tokenContract = new ethers.Contract(launch.tokenAddress, tokenABI, provider);
    const userTokenBalance = await tokenContract.balanceOf(userAddress);
    console.log('3. 用户代币余额:', ethers.formatUnits(userTokenBalance, 18));
    
    // 4. 获取用户授权额度
    const allowance = await tokenContract.allowance(userAddress, CONTRACT_ADDRESS);
    console.log('4. 用户授权额度:', ethers.formatUnits(allowance, 18));
    console.log('');
    
    // 5. 计算应获得的BNB数量
    try {
      const bnbToReceive = await contract.calculateBNBForTokens(launchId, tokenAmount);
      console.log('5. 计算结果:');
      console.log('   - 应获得BNB:', ethers.formatEther(bnbToReceive), 'BNB');
      console.log('   - 合约余额是否足够:', contractBalance >= bnbToReceive ? '✅ 是' : '❌ 否');
      console.log('   - 余额差额:', ethers.formatEther(contractBalance - bnbToReceive), 'BNB');
      
      // 6. 检查各项条件
      console.log('\n6. 条件检查:');
      console.log('   - 用户代币余额足够:', userTokenBalance >= tokenAmount ? '✅' : '❌');
      console.log('   - 用户授权额度足够:', allowance >= tokenAmount ? '✅' : '❌');
      console.log('   - 合约BNB余额足够:', contractBalance >= bnbToReceive ? '✅' : '❌');
      console.log('   - Launch未启动:', !launch.launched ? '✅' : '❌');
      console.log('   - Launch未取消:', !launch.cancelled ? '✅' : '❌');
      
    } catch (error) {
      console.log('❌ 计算BNB数量时出错:', error.message);
    }
    
    // 7. 获取当前代币价格
    try {
      const currentPrice = await contract.getCurrentTokenPrice(launchId);
      console.log('\n7. 当前代币价格:', ethers.formatEther(currentPrice), 'BNB per token');
    } catch (error) {
      console.log('❌ 获取价格时出错:', error.message);
    }
    
  } catch (error) {
    console.error('❌ 检查失败:', error.message);
  }
}

checkSellConditions();
